package com.knowif.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.knowif.dao.TUserMapper;
import com.knowif.enumInfo.InfoStatusEnum;
import com.knowif.enumInfo.UserEnum;
import com.knowif.pojo.TUser;
import com.knowif.pojo.TUserExample;
import com.knowif.pojo.TutorInfo;
import com.knowif.pojo.UserEducationExperience;
import com.knowif.pojo.UserWechat;
import com.knowif.system.model.RestBean;
import com.knowif.util.commonUtil.IntegerUtil;

/**
 * @author xingyao
 * @Description: 用户查询功能
 */
@Service
public class User_service {

	@Autowired
	public TUserMapper userMapper;

	@Autowired
	public Tutor_service tutor_service;
	
	@Autowired
	private UserCollect_service userCollect_service;
	
	@Autowired
	private UserComment_service comment_service;

	@Autowired
	private UserEducationExperience_service educationExperience_service;
	
	@Autowired
	private UserWechat_service userWechat_service;
	
	/**
	 * 保存普通用户
	 * @param user
	 * @return
	 */
	public RestBean<?> saveNormalUser(TUser user) {
		TUserExample usersExample = new TUserExample();
		usersExample.createCriteria().andOpenidEqualTo(user.getOpenid());
		List<TUser> users = selectByTUserExampleAndNOTVirtualUser(usersExample);
		if (users != null && !users.isEmpty()) {
			return RestBean.buildSuccess(users.get(0));
		}
		user.setUserType(UserEnum.USER.getNumber());
		int insetUser = userMapper.insert(user);
		if(insetUser != 1){
			return RestBean.buildError("添加失败", user);
		}
		return RestBean.buildSuccess(user);
	}

	/**
	 * 保存用户
	 * @param user
	 * @return
	 */
	public void save(TUser user) {
		userMapper.insert(user);
	}
	
	  /**
     * 微信小程序登录，不存在用户则把openid返回
     * @param code
     * @return
     */
	public TUser login(String codeSessionStr, String openId) {
		TUserExample usersExample = new TUserExample();
        usersExample.createCriteria().andOpenidEqualTo(openId);
        List<TUser> users = selectUser(usersExample);
        //加入微信表，关联unionid
        JSONObject obj = JSONObject.parseObject(codeSessionStr);
        String unionid = obj.getString("unionid");
        String openid = obj.getString("openid");
        List<UserWechat> userWechats = userWechat_service.getByOpenIdAndUnionId(unionid, openid);
        if(userWechats == null || userWechats.isEmpty()){
        	UserWechat userWechat = new UserWechat();
            userWechat.setUnionid(unionid);
            userWechat.setMini(openid);
            userWechat_service.insertSelective(userWechat);
        }else{
        	UserWechat userWechat = new UserWechat();
            userWechat.setUnionid(unionid);
            userWechat.setMini(openid);
            userWechat_service.updateByPrimaryKeySelective(userWechat);
        }
        if(users != null && !users.isEmpty()){
        	return  users.get(0);
        }else{
        	return null;
        }
	}
	
	
	
	
	public List<TUser> selectByUserIdsAndNotDelete(List<Integer> userIds) {
		if(userIds == null || userIds.isEmpty()){
			return new ArrayList<TUser>();
		}
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andIdIn(userIds).andIsDelNotEqualTo(InfoStatusEnum.DELETE.getStatus());
		List<TUser> tusers = selectByTUserExampleAndNOTVirtualUser(tUserExample);
		return tusers;
	}
	
	public List<TUser> selectByTUserExampleAndNOTVirtualUser(TUserExample tUserExample) {
		if(tUserExample == null){
			return new ArrayList<TUser>();
		}
		if(tUserExample.getOredCriteria() != null){
			tUserExample.getOredCriteria().get(0).andUserTypeNotEqualTo(UserEnum.VIRTUAL_USER.getNumber());
		}
		return userMapper.selectByExample(tUserExample);
	}
	
	
	public List<TUser> selectByTUserExample(TUserExample tUserExample) {
		return userMapper.selectByExample(tUserExample);
	}


	/**
	 * 条件查询用户
	 * @param userExample
	 * @return
	 */
	public List<TUser> selectUser(TUserExample userExample) {
		List<TUser> users = selectByTUserExampleAndNOTVirtualUser(userExample);
		if (users != null && users.isEmpty()) {
			return null;
		}
		return users;
	}
	
	
	/**
	 * 条件查询用户
	 * @param userExample
	 * @return
	 */
	public TUser selectById(Integer userId) {
		if(IntegerUtil.isEmpty(userId)){
			return null;
		}
		return userMapper.selectByPrimaryKey(userId);
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  通过userIds查找用户信息
	 * @param userIds
	 * @return
	 */
	public List<TUser> selectByUserIds(List<Integer> userIds){
		if(userIds == null || userIds.isEmpty()){
			return new ArrayList<TUser>();
		}
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andIdIn(userIds);
		return selectByTUserExample(tUserExample);
	}

	/**
	 * @author: xingyao
	 * @Description: 删除用户操作，逻辑删除，其中该用户对应的订单信息，评论信息。如果是导师还得删除导师的基本信息，及其模糊查询信息
	 *               该功能只能是管理员调用，用于防止别人恶意注册刷评论。
	 * @param tUser
	 * @return
	 */
	@Transactional
	public RestBean<?> deleteUser(TUser tUser) {
		if (tUser == null) {
			throw new RuntimeException("被删除的用户信息不能为空");
		}
		// 将tUser表中的isdelete置位1，标识已经删除，这样导师的信息也就找不到了
		tUser.setIsDel(InfoStatusEnum.DELETE.getStatus());
		int result = userMapper.updateByPrimaryKey(tUser);
		if (result == 0) {
			throw new RuntimeException("删除用户信息失败");
		}
		try{
			// 逻辑删除：更新评论的物理状态
			comment_service.deleteByUserid(tUser.getId());
			
			//删除用户收藏的数据
			userCollect_service.deleteCollectByUserId(tUser.getId());
		}catch(Exception e){
			return RestBean.buildError("删除数据失败");
		}
		// 删除恶意用户分享的红包金额（不明确需求，暂时不做）
		return RestBean.buildSuccess("删除数据成功");
	}
	
	
	
	/**
	 * @author: xingyao
	 * @Description: 批量删除用户操作，逻辑删除，其中该用户对应的订单信息，评论信息。如果是导师还得删除导师的基本信息，及其模糊查询信息
	 *               该功能只能是管理员调用，用于防止别人恶意注册刷评论。
	 * @param tUser
	 * @return
	 */
	@Transactional
	public RestBean<?> deleteUsers(List<Integer> userIds) {
		if (userIds == null) {
			throw new RuntimeException("被删除的用户信息不能为空");
		}
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andIdIn(userIds);
		TUser tUser = new TUser();
		tUser.setIsDel(InfoStatusEnum.DELETE.getStatus());
		int result = userMapper.updateByExample(tUser, tUserExample);
		if (result == 0) {
			throw new RuntimeException("删除用户信息失败");
		}
		try{
			// 逻辑删除：更新评论的物理状态
			comment_service.deleteByUserid(tUser.getId());
			
			//删除用户收藏的数据
			userCollect_service.deleteCollectByUserId(tUser.getId());
		}catch(Exception e){
			return RestBean.buildError("删除数据失败");
		}
		// 删除恶意用户分享的红包金额（不明确需求，暂时不做）
		return RestBean.buildSuccess("删除数据成功");
	}
	
	
	
	/**
	 * @author: xingyao 
	 * @Description:  用于个人中心查找
	 * @param tutorId
	 * @return
	 */
	public RestBean<?> selectUserInfo(Integer userId){
		if(userId  == null){
			return RestBean.buildError("请输入用户id");
		}
		TUser tUser = userMapper.selectByPrimaryKey(userId);
		if(tUser == null){
			return RestBean.buildError("没有找到该用户");
		}else if(InfoStatusEnum.isDelete(tUser.getIsDel())){
			return RestBean.buildError("改用户已经被管理员删除，请与管理员联系");
		}
		List<TutorInfo> tutorInfos = null;
		if(UserEnum.isTutor(tUser.getUserType())){
			tutorInfos  = tutor_service.selectByUserId(userId);
			List<Integer> tutorIds = TutorInfo.getTutorIds(tutorInfos);
			List<UserEducationExperience> educationExperiences = educationExperience_service.selectByTutorIds(tutorIds);
			TutorInfo.andUserEducationExperiences(tutorInfos, educationExperiences);
			
			if(tutorInfos != null){
				for(TutorInfo tutorInfo : tutorInfos){
					if(tutorInfo.getUserId() == userId){
						tutorInfo.settUser(tUser);
					}
				}
			}
			return RestBean.buildSuccess(tutorInfos);
		}else{
			return RestBean.buildSuccess(tUser);
		}
	}

	/**
	 * 更新用户信息
	 * @param tUser
	 */
	public int updateUserInfo(TUser tUser){
		return userMapper.updateByPrimaryKeySelective(tUser);
	}

}
